import json

from django.shortcuts import render, redirect
from book.models import Book
from reader.models import Reader, ReaderDetail
from django.views import View
from utils.MyPage import Pagination


def main(request):
    return render(request, 'reader_main.html')


# Create your views here.
def check_book(request):
    current_page = request.GET.get('page', 1)
    book_data_all = Book.objects.all()
    all_count = book_data_all.count()
    page_obj = Pagination(current_page=current_page, all_count=all_count, per_page_num=5, pager_count=5)
    book_data = book_data_all[page_obj.start:page_obj.end]
    page_html = page_obj.page_html()
    # book_obj_all = Book.objects.all()
    return render(request, 'reader_book.html', locals())


class Register(View):
    def get(self, request):
        reader_all = Reader.objects.all()
        return render(request, 'reader_register.html', locals())

    def post(self, request):
        data_code = request.body
        data = json.loads(data_code)
        reader_info, reader_detail = get_info(data)
        detail_obj = ReaderDetail.objects.create(**reader_detail)
        Reader.objects.create(detail=detail_obj, **reader_info)
        return redirect('reader:main')


def get_info(data):
    reader_info = {
        'username': data.get('username'),
        'password': data.get('password')
    }
    reader_detail = {
        'email': data.get('email'),
        'desc': data.get('desc'),
        'birthday': data.get('birthday')
    }
    return reader_info, reader_detail


class EditReader(View):
    def get(self, request):
        reader_all = Reader.objects.all()
        reader_detail_all = ReaderDetail.objects.all()

    def post(self, request):
        ...
